package org.nch.videoLauncher.presenter;

import org.nch.videoLauncher.view.IAddEditVideoView;
import org.nch.videoLauncher.task.VideoItemTask;
import org.nch.videoLauncher.task.ProfileUtil;
import org.nch.videoLauncher.domain.*;

import java.util.*;
import java.io.File;
import java.text.SimpleDateFormat;

/**
 * Created by IntelliJ IDEA.
 * User: bill
 * Date: Nov 18, 2008
 * Time: 1:56:43 PM
 * To change this template use File | Settings | File Templates.
 */
public class AddEditVideoPresenter {

    private IAddEditVideoView view;
    private VideoItemTask task;
    public List<VideoItem> videoItems;
    private MainWindowPresenter mainWindowPresenter;
    private VideoItem currentVideoItem;
    private boolean fileListChanged;

    public AddEditVideoPresenter(IAddEditVideoView aevv, MainWindowPresenter mwPresenter){
        this.view = aevv;
        this.mainWindowPresenter = mwPresenter;
        this.task = new VideoItemTask();
        this.videoItems = task.getAllVideoItems();
        view.setVideoList(this.videoItems);
        view.setDetailsEnabled(false);
    }
    
    // selection has changed in the list of video items

    public void selectionChanged(Integer index){
//        System.out.println("selection index: " + index);

        view.clearDetails();

        currentVideoItem = videoItems.get(index);

        view.setDetailsEnabled(true);

        view.setDetailTitle(currentVideoItem.getTitle());
        view.setDetailFilename(currentVideoItem.getFilename());

        if (currentVideoItem.getFilename() != null)
            view.setPlayNowEnabled(true);
        else
            view.setPlayNowEnabled(false);        

        view.setDetailUrl(currentVideoItem.getUrl());

        if (currentVideoItem.getUrl() != null)
            view.setBrowseUrlEnabled(true);
        else
            view.setBrowseUrlEnabled(false);

        view.setDetailDescription(currentVideoItem.getDescription());
        view.setDetailKeywords(currentVideoItem.getKeywords());

        if (currentVideoItem.getRunTime() == "null")
            view.setRuntime("");
        else
            view.setRuntime(currentVideoItem.getRunTime());

        if (currentVideoItem.getImdbInfo() != null){
            view.setImdbKey(currentVideoItem.getImdbInfo().getImdbKey());
            view.setImdbTitle(currentVideoItem.getImdbInfo().getTitle());
            view.setImdbRating(currentVideoItem.getImdbInfo().getRating());
            view.setImdbDate(currentVideoItem.getImdbInfo().getDate());
            view.setImdbDirected(currentVideoItem.getImdbInfo().getDirectedBy());
            view.setImdbWritten(currentVideoItem.getImdbInfo().getWrittenBy());
            view.setImdbMpaa(currentVideoItem.getImdbInfo().getMpaa());
            view.setImdbCast(currentVideoItem.getImdbInfo().getCast());

            if (currentVideoItem.getImdbInfo().getImdbKey() != null)
                view.setFetchEnabled(true);
            else
                view.setFetchEnabled(false);

            if (currentVideoItem.getImdbInfo().getCover() != null){
                view.setCoverImage(currentVideoItem.getImdbInfo().getCover());
            }

        }

        if (currentVideoItem.getSportsEvent() != null){
            view.setSportSport(currentVideoItem.getSportsEvent().getSport());
            view.setSportTeam(currentVideoItem.getSportsEvent().getTeam());
            view.setSportSeason(currentVideoItem.getSportsEvent().getSeason());
            if (currentVideoItem.getSportsEvent().getDate() != null){
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd");
                view.setSportDate(formatter.format(currentVideoItem.getSportsEvent().getDate()));
            }
            view.setSportCompetition(currentVideoItem.getSportsEvent().getCompetition());
        }

        if (currentVideoItem.getTvInfo() != null){
            view.setTvShow(currentVideoItem.getTvInfo().getShow());
            if (String.valueOf(currentVideoItem.getTvInfo().getSeason()) == "null"){
                view.setTvSeason("");
            } else {
                view.setTvSeason(String.valueOf(currentVideoItem.getTvInfo().getSeason()));
            }
            if (String.valueOf(currentVideoItem.getTvInfo().getEpisode()) == "null"){
                view.setTvEpisode("");
            } else {
                view.setTvEpisode(String.valueOf(currentVideoItem.getTvInfo().getEpisode()));
            }
        }

        // set up the files view

        for (VideoFile vf : currentVideoItem.getFiles()){
            view.addFileListElement(vf.getFilename());
        }
        if (currentVideoItem.getFiles().size() > 0)
            view.setAddFileButtonEnabled(true);
        view.setCurrentFileSelection(currentVideoItem.getFiles().size()-1);
        fileListChanged = false;

    }

    public void exit(){
        mainWindowPresenter.setNavButtonView();
    }

    public void detailsChanged(){

        SportsEvent se;
        TVInfo tv;
        IMDBInfo imdb;

        // TODO:  don't allow save for items with blank required fields

        if (getDetailHasChanged()){

            currentVideoItem = videoItems.get(view.getCurrentSelection());

            // get the general and description details

            currentVideoItem.setTitle(view.getDetailTitle());
            currentVideoItem.setFilename(view.getDetailFilename());
            currentVideoItem.setUrl(view.getDetailUrl());
            currentVideoItem.setDescription(view.getDescription());
            currentVideoItem.setKeywords(view.getKeywords());
            if (!view.getRuntime().equals("")){
                currentVideoItem.setRunTime(view.getRuntime());
            }

            // get the imdb details

            if (currentVideoItem.getImdbInfo() == null){
                imdb = new IMDBInfo();
                currentVideoItem.setImdbInfo(imdb);
            } else {
                imdb = currentVideoItem.getImdbInfo();
            }
            imdb.setImdbKey(view.getImdbKey());
            imdb.setTitle(view.getImdbTitle());
            imdb.setRating(view.getImdbRating());
            imdb.setDate(view.getImdbDate());
            imdb.setDirectedBy(view.getImdbDirected());
            imdb.setWrittenBy(view.getImdbWritten());
            imdb.setMpaa(view.getImdbMpaa());
            imdb.setCast(view.getImdbCast());

            // get the sports event details

            if (currentVideoItem.getSportsEvent() == null){
                se = new SportsEvent();
                currentVideoItem.setSportsEvent(se);
            } else {
                se = currentVideoItem.getSportsEvent();
            }
            se.setSport(view.getSportSport());
            se.setTeam(view.getSportTeam());
            se.setSeason(view.getSportSeason());
            se.setCompetition(view.getSportCompetition());
            if (!view.getSportDate().equals("")){
                se.setDate(parseDateFromText(view.getSportDate()));                
            }


            // get the tv show details

            if (currentVideoItem.getTvInfo() == null){
                tv = new TVInfo();
                currentVideoItem.setTvInfo(tv);
            } else {
                tv = currentVideoItem.getTvInfo();
            }
            tv.setShow(view.getTvShow());
            if (!view.getTvSeason().equals("")){
                tv.setSeason(Integer.parseInt(view.getTvSeason()));
            }
            if (!view.getTvEpisode().equals("")){
                tv.setEpisode(Integer.parseInt(view.getTvEpisode()));
            }

            // update file collection
            // TODO - this is NOT corect way to manage files collection

            // vi.addFile(view.getDetailFilename());

            // save the task

            task.saveVideoItem(currentVideoItem);

            fileListChanged = false;
        } 
    }

    private Date parseDateFromText(String dateText){

        int year = Integer.parseInt(dateText.substring(0, 4));
        int month = Integer.parseInt(dateText.substring(5, 7));
        int dayofmonth = Integer.parseInt(dateText.substring(8, 10));

        Calendar cal = new GregorianCalendar(year, month - 1, dayofmonth);

        return cal.getTime();

    }

    public void addNewItem(){
        VideoItem newItem = new VideoItem("", "");
        videoItems.add(0, newItem);
        view.clearDetails();
    }

    public void deleteItem(Integer index){
        view.clearDetails();
        view.setDetailsEnabled(false);
        task.deleteVideoItem(videoItems.get(index));
        videoItems.remove((int)index);

    }

    public void browseFileButtonPressed(){
        if (view.isFileSelected(ProfileUtil.getProfile().getBaseVideoPath())){
            view.setDetailFilename(view.getSelectedFilename());
            if (videoItems.get(view.getCurrentSelection()).getFiles() == null || videoItems.get(view.getCurrentSelection()).getFiles().size() == 0){
                videoItems.get(view.getCurrentSelection()).addFile(view.getSelectedFilename());
                view.addFileListElement(view.getSelectedFilename());
                fileListChanged = true;
            } else {
                videoItems.get(view.getCurrentSelection()).getFiles().get(0).setFilename(view.getSelectedFilename());
                view.updateFileListElement(0, view.getSelectedFilename());
                fileListChanged = true;
            }
            detailsChanged();
        }
    }

    public void playItem(Integer index){
        task.playVideoItem(videoItems.get(index));
    }

    public void openUrl(Integer index){
        task.openUrl(videoItems.get(index));
    }

    public boolean getDetailHasChanged() {

        Integer currentTableRow = view.getCurrentSelection();

//        System.out.println("Checking for changes in row: " + currentTableRow);

        if (currentTableRow == null || currentTableRow == -1)
            return false;

        VideoItem currentVideoItem = videoItems.get(currentTableRow);

        if (view.getDetailTitle().equals("") && view.getDetailFilename().equals(""))
            return false;

        if (!view.getDetailTitle().equals(currentVideoItem.getTitle()))
            return true;   // title has changed

        if (!view.getDetailFilename().equals(currentVideoItem.getFilename()))
            return true;   // filename has changed

        if ((!view.getDetailUrl().equals("")) && (!(view.getDetailUrl().equals(currentVideoItem.getUrl()))))
            return true;

        if ((!view.getDescription().equals("")) && (!(view.getDescription().equals(currentVideoItem.getDescription()))))
            return true;

        if ((!view.getKeywords().equals("")) && (!(view.getKeywords().equals(currentVideoItem.getKeywords()))))
            return true;

        if ((!view.getRuntime().equals("")) && (!(view.getRuntime().equals(currentVideoItem.getRunTime()))))
            return true;

        if (!view.getImdbKey().equals("") && !view.getImdbKey().equals(currentVideoItem.getImdbInfo().getImdbKey()))
            return true;        

        if (!view.getImdbTitle().equals("") && !view.getImdbTitle().equals(currentVideoItem.getImdbInfo().getTitle()))
            return true;

        if (!view.getImdbRating().equals("") && !view.getImdbRating().equals(currentVideoItem.getImdbInfo().getRating()))
            return true;

        if (!view.getImdbDate().equals("") && !view.getImdbDate().equals(currentVideoItem.getImdbInfo().getDate()))
            return true;

        if (!view.getImdbDirected().equals("") && !view.getImdbDirected().equals(currentVideoItem.getImdbInfo().getDirectedBy()))
            return true;

        if (!view.getImdbWritten().equals("") && !view.getImdbWritten().equals(currentVideoItem.getImdbInfo().getWrittenBy()))
            return true;

        if (!view.getImdbMpaa().equals("") && !view.getImdbMpaa().equals(currentVideoItem.getImdbInfo().getMpaa()))
            return true;

        if (!view.getImdbCast().equals("") && !view.getImdbCast().equals(currentVideoItem.getImdbInfo().getCast()))
            return true;

        if (!view.getSportSport().equals("") && !view.getSportSport().equals(currentVideoItem.getSportsEvent().getSport()))
            return true;

        if (!view.getSportTeam().equals("") && !view.getSportTeam().equals(currentVideoItem.getSportsEvent().getTeam()))
            return true;

        if (!view.getSportSeason().equals("") && !view.getSportSeason().equals(currentVideoItem.getSportsEvent().getSeason()))
            return true;

        if (!view.getSportCompetition().equals("") && !view.getSportCompetition().equals(currentVideoItem.getSportsEvent().getCompetition()))
            return true;

        if (!view.getSportDate().equals("") && !(parseDateFromText(view.getSportDate()) == currentVideoItem.getSportsEvent().getDate()))
            return true;

        if (!view.getTvShow().equals("") && !view.getTvShow().equals(currentVideoItem.getTvInfo().getShow()))
            return true;

        if (!view.getTvSeason().equals("") && !view.getTvSeason().equals(String.valueOf(currentVideoItem.getTvInfo().getSeason())))
            return true;

        if (!view.getTvEpisode().equals("") && !view.getTvEpisode().equals(String.valueOf(currentVideoItem.getTvInfo().getEpisode())))
            return true;

        if (fileListChanged)
            return true;

        return false;

    }

    public void imdbFetchRequested(){

        if (!(view.getImdbKey().equals(""))) {
            VideoItem currentVideoItem = videoItems.get(view.getCurrentSelection());
            IMDBInfo imdbInfo = new IMDBInfo();
            imdbInfo.setImdbKey(view.getImdbKey());
            currentVideoItem.setImdbInfo(imdbInfo);
            task.loadIMDBData(currentVideoItem);
            task.saveVideoItem(currentVideoItem);
            this.selectionChanged(view.getCurrentSelection());
        }
    }

    public void addFileButtonPressed(){
        currentVideoItem = videoItems.get(view.getCurrentSelection());
        currentVideoItem.addFile("New file - use Browse to choose");
        view.addFileListElement("New file - use Browse to choose");
        view.setAddFileButtonEnabled(true);
        view.setDeleteFileButtonEnabled(true);
        view.setBrowseFileButtonEnabled(true);
        fileListChanged = true;
    }

    public void deleteFileButtonPressed(){

        currentVideoItem = videoItems.get(view.getCurrentSelection());
         if (currentVideoItem.deleteFileAtIndex(view.getCurrentFileSelection())){
            view.removeFileListElement(view.getCurrentFileSelection());
            fileListChanged = true;
            if (currentVideoItem.getFiles().size() == 1)
                view.setDeleteFileButtonEnabled(false);             
         }
    }

    public void browseFileListButtonPressed(){
//        if (view.isFileSelected(ProfileUtil.getProfile().getBaseVideoPath() + File.separator + currentVideoItem.getNextFileLocation())){
        if (view.isFileSelected(ProfileUtil.getProfile().getBaseVideoPath())){
            view.setBrowseFileText(view.getSelectedFilename());
            if (view.getCurrentFileSelection() > 0){  // file was selected, so let's update it
                view.updateFileListElement(view.getCurrentFileSelection(), view.getSelectedFilename());
                currentVideoItem = videoItems.get(view.getCurrentSelection());
                currentVideoItem.getFiles().get(view.getCurrentFileSelection()).setFilename(view.getSelectedFilename());
                fileListChanged = true;
            }
        }
    }

    public void fileSelectionChanged(Integer index){

        view.setCurrentFileSelection(index);
        view.setBrowseFileText(currentVideoItem.getFiles().get(index).getFilename());
        if (index > 0 ){
            view.setDeleteFileButtonEnabled(true);
            view.setBrowseFileButtonEnabled(true);
        } else {
            view.setDeleteFileButtonEnabled(false);
            view.setBrowseFileButtonEnabled(false);
        }
    }

    public void copyTvShowPressed(){
        currentVideoItem = videoItems.get(view.getCurrentSelection());
        if (currentVideoItem.getTvInfo() != null){
            videoItems.add(0, currentVideoItem.copyTvShow());          
        }
    }

}
